package action;

import bean.User;
import com.opensymphony.xwork2.ActionSupport;

import dao.UserDAOImpl;
import service.UserService;
import service.UserServiceImpl;
import tool.DatabaseManager;

import java.sql.SQLException;
import java.util.List;

public class UserAction extends ActionSupport {
    private static final long serialVersionUID = 6338902291938200168L;
    private UserService userService;
    private List<User> users;
    private User user;
    
    {
        try {
            userService = new UserServiceImpl(new UserDAOImpl(DatabaseManager.getConnection()));
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    public List<User> getUsers() {
        return users;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public String execute() throws Exception {
        users = userService.queryAll();
        return SUCCESS;
    }

    public String add() throws Exception {
        userService.add(user);
        return "add";
    }

    public String edit() throws SQLException, ClassNotFoundException {
        user = userService.query(user.getUserId());
        return "edit";
    }

    public String modify() throws Exception {
        userService.modify(user);
        return "modify";
    }

    public String remove() throws SQLException, ClassNotFoundException {
        userService.remove(user.getUserId());
        return "remove";
    }
}
